package com.hmall.order.listener;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.hmall.common.config.ItemFrignConfig;
import com.hmall.order.mapper.OrderDetailMapper;
import com.hmall.order.mapper.OrderNumIdMapper;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import com.hmall.order.pojo.OrderNum;
import com.hmall.order.service.impl.OrderService;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 监听延时消息队列
 */
@Component
public class OrderListener {
    @Autowired
    private ItemFrignConfig itemFrignConfig;
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private OrderNumIdMapper orderNumIdMapper;
    @RabbitListener(queues = "delay.queue")
    public void listenOrderDelay(String orderId){
        Long id = Long.valueOf(orderId);
        Order order = orderService.getById(id);
//        获取订单状态
        Integer status = order.getStatus();
        if(status!=1){
            return;
        }
//        根据订单Id查询订单详情
        LambdaQueryWrapper<OrderDetail> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(OrderDetail::getOrderId,id);
        OrderDetail orderDetail = orderDetailMapper.selectOne(lambdaQueryWrapper);
//        获取商品数量
        Integer num = orderDetail.getNum();
//        判断订单状态
        if(status==1){
//            为1则设置为取消订单
            UpdateWrapper<Order> wrapper = new UpdateWrapper<>();
            wrapper.eq("id",id);
            wrapper.set("status",5);
            orderService.update(null,wrapper);
//            根据订单id查询下单前库存
            OrderNum orderNum = orderNumIdMapper.selectById(id);
            Integer num1 = orderNum.getNum();
//            恢复库存
            itemFrignConfig.updateByItemId(orderDetail.getItemId(),num1);
        }

    }
}
